//
//  Bar.m
//  testerApp
//
//  Created by Stephen Laughton on 06/11/09.
//  Copyright 2009 Black Cloud Studio. All rights reserved.
//

#import "Bar.h"


@implementation Bar

@synthesize noteTree;
@synthesize barView;
@synthesize currentNotes;

/*
 Initiates bar with 4/4 NoteTree, empty currentNotes, and clear background
 */
-(id)init {
	if (self = [super init]) {
		noteTree = [[NoteTree alloc] init];
		currentNotes = [[NSMutableArray alloc] init];
		barView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 480, 232)];
		[barView setBackgroundColor: [UIColor clearColor]];
		[self resetCurrentNotes];
	}
	return self;
}

- (void)drawBar {
	for (NoteNode* node in currentNotes) {
		if (node.isNote) {
			[barView bringSubviewToFront:node.button];
		}
		[node drawNode];
	}
}

- (void)clearBar {
	[noteTree clearTree];
}

/*
 Returns an array of all correct note nodes currently in bar
 */
-(void)resetCurrentNotes {
	for (NoteNode* node in currentNotes) {
		NSLog(@"hiding note %@", node);
		[node.button setHidden:TRUE];
		[node.rest setHidden:TRUE];
	}
	[currentNotes removeAllObjects];
	[self traverseForNotesFromNode: noteTree.wholeNode];
}

/*
 Used by setCurrentNotes method
 */
- (void)traverseForNotesFromNode:(NoteNode*)currentNode {
	if (currentNode.isNote == FALSE && currentNode.isRest == FALSE){
		for (NoteNode* child in currentNode.children){
			[self traverseForNotesFromNode:child];
		}
		return;
	}
	else if (currentNode.isNote == TRUE || currentNode.isRest == TRUE) {
		[self.currentNotes addObject:currentNode];
	}
	else {
		NSLog(@"ERROR IN traverseForNotesFromNode");
	}
	return;
}

/*
 Modifies Bar's NoteTree to represent that node becoming a Note with given pitch
 */
-(void)insertNoteAt:(NoteNode*)insertNode withPitch:(int)insertPitch andButton:(NodeButton*)insertButton {
	NSLog(@"adding note at %@ with pitch %i", insertNode, insertPitch);
	insertNode.isNote = TRUE;
	insertNode.isRest = FALSE;
	insertNode.note.notePitch = insertPitch;
	insertNode.button = insertButton;
	for (NoteNode* child in insertNode.children){
		[child setDescendants];
	}
	[insertNode.parent setAncestors];
	[self resetCurrentNotes];
}

/*
 Modifies Bar's NoteTree to represent that node becoming a Rest
 */
-(void)removeNoteAt:(NoteNode*)removeNode {
	removeNode.isNote = FALSE;
	removeNode.isRest = TRUE;
	
	for (NoteNode* child in removeNode.children){
		[child setDescendants];
	}
	[removeNode.parent resetAncestors];
	[self resetCurrentNotes];
}

-(id)initWithCoder:(NSCoder*)coder {
	noteTree = [[coder decodeObjectForKey:@"noteTree"] retain];
	barView = [[coder decodeObjectForKey:@"barView"] retain];
	currentNotes = [[NSMutableArray alloc] initWithCapacity: 0];
	barView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 480, 232)];
	[barView setBackgroundColor: [UIColor clearColor]];
	
	[self resetCurrentNotes];
	return self;
}

-(void)encodeWithCoder:(NSCoder*)encoder {
	[encoder encodeObject: noteTree forKey:@"noteTree"];
	[currentNotes release];
}

@end
